package boun.swe.bob.service;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * This controller is used for message page actions
 */
public class MessageController extends BaseController {
    @RequestMapping(method = RequestMethod.GET)
        public ModelAndView showPage(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
            Map<String, Object> myModel = Maps.newHashMap();
            myModel.put("user", userDao.findByPrimaryKey(getLoggedInUser(httpServletRequest).getUserId()));
            myModel.put("himself",true);
            myModel.put("selectedUserId",httpServletRequest.getParameter("toUserId"));
        if(httpServletRequest.getParameter("toUserId") != null){
           myModel.put("selectedUser", userDao.findByPrimaryKey(Integer.parseInt(httpServletRequest.getParameter("toUserId"))));
        }
            httpServletRequest.getSession().setAttribute("toUserId", httpServletRequest.getParameter("toUserId"));
            return new ModelAndView("newMessage", "model", myModel);
        }

     /**
     * Handles HTTP POST action for sending a message
     *
     * @param httpServletRequest http request
     * @param httpServletResponse http response
     * @return the result message
     */
    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView sendMessage(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        Map<String, Object> myModel = Maps.newHashMap();

        //String fromMsgId =httpServletRequest.getParameter("from_message_id");

         String toUserId=  httpServletRequest.getParameter("select_FriendId");
                 //httpServletRequest.getSession().getAttribute("toUserId").toString();
         String msgTitle = httpServletRequest.getParameter("msgTitle");
         String msgBody = httpServletRequest.getParameter("msgBody");

        //String toUserId = httpServletRequest.getParameter("toUserId");

         if(!Strings.isNullOrEmpty(msgTitle) && !Strings.isNullOrEmpty(msgBody) && !Strings.isNullOrEmpty(toUserId)) {
             userMessageDao.addNewRootMessage(getLoggedInUser(httpServletRequest).getUserId(),Integer.parseInt(toUserId),msgTitle,msgBody);
             myModel.put("retVal","Message Sent!");
        }
             if(null != getLoggedInUser(httpServletRequest).getUserId()) {

                myModel.put("user", userDao.findByPrimaryKey(getLoggedInUser(httpServletRequest).getUserId()));
                myModel.put("himself",  true );

            }

            return new ModelAndView("newMessage", "model", myModel);
        }
}